package top.likeqc.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.likeqc.common.lang.Result;
import top.likeqc.entity.Target;
import top.likeqc.service.ICourseService;
import top.likeqc.service.ITargetService;

import java.util.List;

/**
 * <p>
 * 课程目标 前端控制器
 * </p>
 *
 * @author likeqc
 * @since 2022-04-14
 */
@RestController
@RequestMapping("/target")
public class TargetController extends BaseController {

    @Autowired
    ITargetService targetService;

    @Autowired
    ICourseService courseService;

    @GetMapping()
    public Result list(String key, Long courseId) {

        QueryWrapper<Target> queryWrapper = new QueryWrapper<Target>().like(StringUtils.isNotBlank(key),
            "content", key);
        if (courseId != null) {
            queryWrapper.eq("course_id", courseId);
        }

        Page<Target> page = targetService.page(getPage(),
            queryWrapper);
        // 根据课程 id 获取课程信息
        page.getRecords().forEach(coursePoint -> {
            coursePoint.setCourse(courseService.getById(coursePoint.getCourseId()));
        });
        return Result.success(page);
    }

    @PostMapping()
    public Result edit(@RequestBody Target target) {
        boolean save = targetService.saveOrUpdate(target);
        if (save) {
            return Result.success();
        } else {
            return Result.fail("新增、修改课程目标，操作失败");
        }
    }

    @DeleteMapping()
    public Result delete(@RequestBody List<Integer> ids) {
        boolean b = targetService.removeByIds(ids);
        if (b) {
            return Result.success();
        } else {
            return Result.fail("删除年级，操作失败");
        }
    }

}
